<?php
declare(strict_types=1);

namespace App\Common\Guard;

use App\Common\Model\Admin\UserModel;
use JetBrains\PhpStorm\ArrayShape;
use Zms\Guard\ModelInterface;
use Zms\Guard\Password;
use Zms\Unit\Str;

class AdminGuard extends UserModel implements ModelInterface
{
    /**
     * 获取会员ID
     * @return int
     * @author 竹林风@875384189 2021/3/2 15:54
     */
    public function getId(): int
    {
        return $this->id;
    }


    /**
     * 获取会员信息
     * @return array
     */
    #[ArrayShape(['id' => "int", 'nickname' => "string", 'account' => 'string', 'avatar' => "string", 'role' => 'array', 'super' => 'bool', 'power' => "array", 'modular' => 'string'])]
    public function userInfo(): array
    {
        return [
            'id' => $this->id ?? 0,
            'nickname' => $this->nickname ?? '',
            'account' => $this->account ?? '',
            'avatar' => $this->avatar ?? '',
            'role' => $this->role ?? [],
            'super' => $this->isSuper(),
            'power' => $this->permissions()
        ];
    }


    /**
     * 权限校验
     * @param mixed|null $auth
     * @return bool
     */
    public function authorize(mixed $auth = null): bool
    {
        if ($auth['sign'] === 'skip' && count($auth['relyon']) === 0) {//跳过和无依赖
            return true;
        }
        $auth['relyon'][] = $auth['sign'];
        return $this->isAuthorize($auth['relyon']);
    }


    /**
     * 生成密码
     * @param string $password 密码
     * @param string $secretKey 加密串
     * @return string
     */
    public function generatePassword(string $password, string $secretKey = ''): string
    {
        return Password::hash($secretKey . $password);
    }


    /**
     * 生产安全密钥
     * @return string
     */
    public function generateSecretKey(): string
    {
        return Str::md5_16(uniqid('pass') . static::class);
    }


    /**
     * 验证密码
     * @param string $password 密码
     * @param string $passwordHas 密码哈希
     * @param string $secretKey 加密串
     * @return bool
     */
    public function verifyPassword(string $password, string $passwordHas, string $secretKey = ''): bool
    {
        return Password::verify($secretKey . $password, $passwordHas);
    }
}